#include <g-bios.h>
#include <net/tftp.h>
#include <core/getopt.h>
#include <flash/part.h>


static void TftpUsage(void)
{
		printf("Usage: tftp [option <value>] [-f] <filename>\n" 
		"\noptions:\n"
		"  -a   \tmemory address [needed in few cases]\n"
		"  -m   \tonly download to memory, without writing to storage\n"
//		"  -f   \tfile name for download\n"
		"  -s   \ttftp server ip\n"
		"  -h   \tthis help\n");
}

static int main(int argc, char *argv[])
{
	int ret, ch;
	int file_flag = 0;
	struct TftpOpt dlopt;
	BOOL isMemOnly = FALSE;
	char *optarg;
	int iOptIdx;
	ULONG ulLoadAddr;


	memset(&dlopt, 0x0, sizeof(dlopt));

	GuNetGetTftpSvr(&dlopt.dwSvrIP);

	if (1 == argc)
	{
		TftpUsage();
		return -EACCES;
	}

	while ((ch = getopt(argc, argv, "a:ms:f:", &optarg)) != -1)
	{
		switch(ch)
		{
		case 'a':
			ret = GuStrToVal(optarg, &ulLoadAddr);
			if (ret < 0)
			{
				TftpUsage();
				return ret;
			}

			dlopt.pLoadAddr = (void *)ulLoadAddr;
			break;

		case 'm':
			isMemOnly = TRUE;
			break;

		case 's':
			ret = GuStrToIp((BYTE *)&dlopt.dwSvrIP, optarg);
			if (ret < 0)
			{
				printf("Invalid IP: %s!\n", optarg);
				return ret;
			}
			break;

		case 'f':
			strncpy(dlopt.szFileName, optarg, MAX_FILE_NAME_LEN);
			dlopt.szFileName[MAX_FILE_NAME_LEN - 1] = '\0';
			file_flag = 1;
			break;

		case 'h':
		default:
			TftpUsage();
			return -EINVAL;
		}
	}


	iOptIdx = get_optind();

	if (iOptIdx < argc)
	{
		if (argc - iOptIdx == 1 && !file_flag)
		{
			strncpy(dlopt.szFileName, argv[iOptIdx], MAX_FILE_NAME_LEN);
			dlopt.szFileName[MAX_FILE_NAME_LEN - 1] = '\0';
		}
		else
		{
			TftpUsage();
			return -EINVAL;
		}
	}


	if (FALSE == isMemOnly)
	{
		struct Partition *pPart;

		pPart = GuPartOpenCur();

		// if (NULL == pPart || PT_BL_GBIOS == GuPartGetType(pPart))
		if (NULL == pPart)
		{
			printf("Invalid Partition!\n");
			return -EINVAL;
		}

		dlopt.pPart = pPart;
	}

	ret = GuNetTftpGetFile(&dlopt);

	if (ret > 0)
		printf("\nTotal %d (0x%08x) bytes received.\n", ret, ret);

	if (FALSE == isMemOnly)
	{
		if (ret > 0)
		{
			GuPartSetImgInfo(dlopt.pPart, dlopt.szFileName, ret);
			GuSysConfStore();
		}

		GuPartClose(dlopt.pPart);
	}

	return ret;
}


INSTALL_APPLICATION(tftp, main, "tftp utility");

